package cn.ddiancan.xddcloud.psc.oss.service;

import java.net.URL;
import java.nio.file.Paths;
import java.util.Date;

import cn.ddiancan.xddcloud.psc.oss.config.XddCloudOssProperties;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class XddCloudOssClientService {

    private final OSSClient ossClient;

    private final XddCloudOssProperties xddCloudOssProperties;

    /**
     * 上传文件
     *
     * @param filePath    文件路径
     * @param ossFileName 文件类型
     * @return PutObjectResponse
     */
    public PutObjectResult uploadFileByPath(String ossFileName, String filePath) {
        return ossClient.putObject(xddCloudOssProperties.getBucketName(), ossFileName, Paths.get(filePath).toFile());
    }

    /**
     * 下载文件
     *
     * @param ossFileName 文件类型
     * @return OSSObject
     */
    public OSSObject downloadFile(String ossFileName) {
        return ossClient.getObject(xddCloudOssProperties.getBucketName(), ossFileName);
    }

    /**
     * 删除文件
     *
     * @param ossFileName 文件路径
     */
    public void deleteFile(String ossFileName) {
        ossClient.deleteObject(xddCloudOssProperties.getBucketName(), ossFileName);
    }

    /**
     * 压缩图片
     * @param objectName
     * @return
     */
    public URL getSignUrl(String objectName) {
        OSSClient ossClient = new OSSClient(xddCloudOssProperties.getEndpoint(), xddCloudOssProperties.getAccessKeyId(), xddCloudOssProperties.getAccessKeySecret());
        String style = "image/auto-orient,1/interlace,1/quality,Q_50/format,jpg";
        Date expiration = new Date((new Date()).getTime() + 3600000L);
        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(xddCloudOssProperties.getBucketName(), objectName, HttpMethod.GET);
        req.setExpiration(expiration);
        req.setProcess(xddCloudOssProperties.getStyle());
        URL signedUrl = ossClient.generatePresignedUrl(req);
        ossClient.shutdown();
        return signedUrl;
    }
}
